package com.frxuexi.user.paging

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.frxuexi.lib_base.room.AskLeave
import com.frxuexi.user.repository.AskRepository

class AskDataSource(askRepository: AskRepository,uid:Int,size: Int):PagingSource<Int,AskLeave>() {
    val askRepository=askRepository
    val uid=uid
    val size=size
    override fun getRefreshKey(state: PagingState<Int, AskLeave>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, AskLeave> {
        return try {
            //取出当前页
            val currentPage= params.key ?: 1

            val list = askRepository.getUserAskList(uid, currentPage,size)

            val askCont = askRepository.getAskCont(uid)
            val total = askCont/size +1

            val nextPage =if(currentPage<total){
                currentPage+1
            }else{
                null
            }


            LoadResult.Page(
                data = list!!,
                prevKey = null,
                nextKey = nextPage
            )
        }
        catch (e:Exception){
            Log.i("===",e.message.toString())
            LoadResult.Error(e)
        }
    }
}